/**
 * 根据一棵树的前序遍历与中序遍历构造二叉树。
 * 前（根）序遍历 ：中左右
 * 中（根）序遍历：左中右
 * <p>
 * 例如，给出
 * <p>
 * 前序遍历 preorder = [3,9,20,15,7]
 * 中序遍历 inorder = [9,3,15,20,7]
 * <p>
 * 注意:
 * 你可以假设树中没有重复的元素。
 */
class Solution {

    public static void main(String[] args) {
        // System.out.println(buildTree(new int[]{1, 2}, new int[]{1, 2}));
        System.out.println(buildTree(new int[]{3, 9, 20, 15, 7}, new int[]{9, 3, 15, 20, 7}));
        // System.out.println(buildTree(new int[]{1, 2, 4, 5, 3, 6, 7}, new int[]{4, 2, 5, 1, 6, 3, 7}));
    }

    /**
     * 用递归的方法去做
     *
     * @param preorder
     * @param inorder
     * @return
     */
    public static TreeNode buildTree(int[] preorder, int[] inorder) {
        int val = preorder[0];
        TreeNode root = new TreeNode(val);
        // 找到inorder中val的位置，这里可以优化，改成用map，这样子查起来快
        int i = 0;
        while (inorder[i] != val) {
            i++;
        }
        root.left = buildTree(preorder, 1, i, inorder, 0, i - 1);
        root.right = buildTree(preorder, i + 1, preorder.length, inorder, i + 1, inorder.length);
        return root;
    }


    public static TreeNode buildTree(int[] preorder, int pos1, int pos2, int[] inorder, int pos3, int pos4) {
        if (pos1 == preorder.length || pos3 > pos4) {
            return null;
        }
        int val = preorder[pos1];
        TreeNode root = new TreeNode(val);
        if (pos1 == pos2) {
            return root;
        }
        // 找到inorder中val的位置
        int i = pos3;
        while (inorder[i] != val) {
            i++;
        }
        i = i - pos3;
        root.left = buildTree(preorder, pos1 + 1, pos1 + i, inorder, pos3, pos3 + i - 1);
        root.right = buildTree(preorder, pos1 + i + 1, pos2, inorder, pos3 + i + 1, pos4);
        return root;
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}